<template>
  <el-dialog append-to-body title="配置权限" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" :visible.sync="visible" :width="'640px'">
    <el-row :gutter="10" v-loading="loading">
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form :inline="true" size="small" @submit.native.prevent>
                <el-form-item>
                    <el-input size="small" placeholder="请输入权限" v-model.trim="searchName" maxlength="30" clearable @input="filteDepartTree"></el-input>
                </el-form-item>
            </el-form>
            <div class="tree_box">
                <el-tree ref="treeRef" default-expand-all show-checkbox node-key="id" :data="menuTreeData" :default-checked-keys="defaultCheckedKeys" :filter-node-method="filterNode" @check="checkOption">
                    <div class="custom-tree-node" slot-scope="{ data }">
                        <span>{{ data.label }}</span>
                    </div>
                </el-tree>
            </div>
        </el-col>
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
            <div>权限组<span v-show="name">“{{name}}”</span>将拥有以下权限：</div>
            <div class="tag_box">
                <el-tag size="small" class="tag_item" closable @close="unCheckOption(item.id)" v-for="item in checkMenuTreeData" :key="'tag' + item.id">{{item.label}}</el-tag>
            </div>
        </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="submitLoading" @click="closeModal()">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="submit()">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { GetRoutersTreeData, GetRoleById, UpdateRole } from '@/views/user-management/services/index';
export default {
  props: ['visible', 'itemId', 'name', 'checked', 'type'],
  data() {
    return {
      searchName: '',
      menuTreeData: [],
      defaultMenuTreeData: [],
      defaultCheckedKeys: [],
      checkMenuTreeData: [],
      flatMenuTreeData: [],
      loading: false,
      submitLoading: false,
      myData: null
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(newValue) {
        if (!newValue) return;
        this.loading = true;
        GetRoutersTreeData()
        .finally(() => this.loading = false)
        .then(data => {
          if (data.code == 200) {
            this.defaultMenuTreeData = JSON.parse(JSON.stringify(data.data));
            this.menuTreeData = this.defaultMenuTreeData.filter(item => item.type == this.type);
            this.flatMenuTreeData = this.flatList(data.data);
          } else {
            this.defaultMenuTreeData = [];
            this.menuTreeData = [];
            this.flatMenuTreeData = [];
          }

          if (this.itemId) {
            this.setData();
          } else {
            this.defaultCheckedKeys = (this.checked && this.checked.length) ? this.checked : [];
            this.defaultCheckedKeys.forEach(item => {
              this.$refs.treeRef.setChecked(item, true, true);
            });
            setTimeout(() => {
              this.checkMenuTreeData = this.$refs.treeRef.getCheckedNodes();
            }, 300);
          }
        })
      }
    }
  },
  methods: {
    setData() {
      this.loading = true;
      GetRoleById({ id: this.itemId })
      .finally(() => (this.loading = false))
      .then(data => {
        if (data.code == 200) {
          this.myData = data.data;
          this.menuTreeData = this.defaultMenuTreeData.filter(item => item.type == data.data.type);
          this.defaultCheckedKeys = data.data.menuIds;
          data.data.menuIds.forEach(item => {
            this.$refs.treeRef.setChecked(item, true, true);
          })
          setTimeout(() => {
            this.checkMenuTreeData = this.$refs.treeRef.getCheckedNodes();
          }, 300);
        }
      })
    },
    checkOption(value, nodes) {
      this.checkMenuTreeData = nodes.checkedNodes;
    },
    unCheckOption(id) {
      this.$refs.treeRef.setChecked(id, false, true);

      this.checkMenuTreeData = this.$refs.treeRef.getCheckedNodes();
    },
    filteDepartTree(value) {
      this.$refs.treeRef.filter(value);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    submit() {
      if (this.itemId) {
        const { id, roleName, roleKey, remark, type, depIds, proId } = this.myData;
        const queryData = {
          id, roleName, roleKey, remark, type, depIds, proId,
          menuIds: this.checkMenuTreeData.map(item => item.id).concat(this.$refs.treeRef.getHalfCheckedKeys())
        };
        UpdateRole(queryData)
          .then(success => {
            this.submitLoading = false;
            if (success.code == 200) {
              this.$message.success('配置权限成功!');
              this.closeModal();
              this.$emit('update', true);
            } else {
              this.$message.error('配置权限失败!');
            }
          })
          .catch(error => {
            this.submitLoading = false;
            this.$message.error(error);
          })
      } else {
        this.$emit('check', {
          allCheck: this.checkMenuTreeData,
          halfCheck: this.$refs.treeRef.getHalfCheckedNodes()
        });
        this.closeModal();
      }
    },
    closeModal() {
      this.$emit('update:visible', false);
      this.searchName = '';
      this.defaultCheckedKeys = [];
      this.checkMenuTreeData = [];
    },
    getMenuList() {
      this.loading = true;
      GetRoutersTreeData()
      .finally(() => this.loading = false)
      .then(data => {
        if (data.code == 200) {
          this.defaultMenuTreeData = JSON.parse(JSON.stringify(data.data));
          this.menuTreeData = data.data;
          this.flatMenuTreeData = this.flatList(data.data);
        } else {
          this.defaultMenuTreeData = [];
          this.menuTreeData = [];
          this.flatMenuTreeData = [];
        }
      })
      .catch(error => {
        this.defaultMenuTreeData = [];
        this.menuTreeData = [];
        this.flatMenuTreeData = [];
      })
    },
    // 扁平化数组
    flatList(list) {
      let array = [];
      const deepFlat = (arr) => {
        arr.forEach(item => {
          if (item.children && item.children.length) {
            deepFlat(item.children);
          }
          let newItem = JSON.parse(JSON.stringify(item));
          newItem.children = [];
          array.push(newItem);
        })
      }

      deepFlat(list);
      return array;
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-tree-node__content {
  height: 38px;
}
.tree_box {
    max-height: 480px;
    overflow-x: hidden;
    overflow-y: auto;
    padding: 10px 0;
}

.tag_box {
  margin: 20px -5px 0;

  .tag_item {
    margin: 5px;
  }
}
</style>